package com.xueyl.springboot;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

@Configuration
@EnableWebSecurity
public class WebSecutiryConfig extends WebSecurityConfigurerAdapter{

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
		.authorizeRequests()
		.antMatchers("/","/home").permitAll()
		.anyRequest().authenticated()
		.and()
		.formLogin()
		.loginPage("/login")
		.permitAll()
		.and()
		.logout()
		.permitAll()
		.and()
		.sessionManagement()
		.maximumSessions(1)
		.expiredSessionStrategy(new DefaultRedirectSessionInformationExpiredStratogy("/login"));
	}
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
		auth
		.inMemoryAuthentication()
		.withUser("user")
		.password("123456")
		.roles("USER");
	}
	
	class DefaultRedirectSessionInformationExpiredStratogy implements SessionInformationExpiredStrategy{

		private final Log logger = LogFactory.getLog(getClass());
		private final String destinationUrl;
		private final RedirectStrategy redirectStrategy;
		
		
		
		public DefaultRedirectSessionInformationExpiredStratogy(String destinationUrl) {
			this(destinationUrl, new DefaultRedirectStrategy());
		}

		public DefaultRedirectSessionInformationExpiredStratogy(String destinationUrl,
				RedirectStrategy redirectStrategy) {
			super();
			this.destinationUrl = destinationUrl;
			this.redirectStrategy = redirectStrategy;
		}


		@Override
		public void onExpiredSessionDetected(SessionInformationExpiredEvent event脴)
				throws IOException, ServletException {
		}
		
	}
	
}
